package cn.example.vip.mall.pay.rocketmq;

import cn.example.vip.mall.pay.entity.PayLog;
import cn.example.vip.mall.pay.service.PayLogService;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * RocketMQ half-message监听器
 */
@RocketMQTransactionListener(txProducerGroup = "RocketMQ-weixin")	// 配置事务的分组
@Component
public class TransactionListener implements RocketMQLocalTransactionListener {
	@Autowired
	private PayLogService payLogService;
	
	/**
	 * 向 RocketMQ 的 Broker 发送 half消息 成功后，调用该方法
	 * @param message 发送的消息
	 * @param o 额外参数
	 * @return 本地事务状态
	 */
	@Override
	public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
		try{
			// 控制本地事务<<<<<<<<<<
			String result = new String((byte[]) message.getPayload());	// 接收数据
			PayLog payLog = JSON.parseObject(result, PayLog.class);		// 转为对象
			payLogService.addPayLog(payLog);							// 执行本地事务
			// >>>>>>>>>>>>>>>>>>>>
		}catch (Exception e){
			e.printStackTrace();
			// 出现异常，回滚事务
			return RocketMQLocalTransactionState.ROLLBACK;
		}
		// 执行成功，提交事务
		return RocketMQLocalTransactionState.COMMIT;
	}
	
	/**
	 * 超时回查
	 * @param message 返回消息
	 * @return 消息状态
	 */
	@Override
	public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
		// TODO: 完成 RocketMQ 组件的完成流程
		return RocketMQLocalTransactionState.COMMIT;
	}
}
